<template>
  <div class="my-goods-view">
    <div class="page-header">
      <h1>我的商品</h1>
      <p>管理你发布的所有商品</p>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <div class="stat-card">
        <div class="stat-icon">📦</div>
        <div class="stat-info">
          <div class="stat-number">{{ stats.total }}</div>
          <div class="stat-label">总商品数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">✅</div>
        <div class="stat-info">
          <div class="stat-number">{{ stats.selling }}</div>
          <div class="stat-label">在售中</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">💰</div>
        <div class="stat-info">
          <div class="stat-number">{{ stats.sold }}</div>
          <div class="stat-label">已售出</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">👁️</div>
        <div class="stat-info">
          <div class="stat-number">{{ stats.totalViews }}</div>
          <div class="stat-label">总浏览量</div>
        </div>
      </div>
    </div>

    <!-- 筛选和操作栏 -->
    <div class="filter-bar">
      <div class="filter-left">
        <el-button-group>
          <el-button 
            :type="statusFilter === 'all' ? 'primary' : ''"
            @click="filterByStatus('all')"
          >
            全部
          </el-button>
          <el-button 
            :type="statusFilter === '在售' ? 'primary' : ''"
            @click="filterByStatus('在售')"
          >
            在售中
          </el-button>
          <el-button 
            :type="statusFilter === '已售' ? 'primary' : ''"
            @click="filterByStatus('已售')"
          >
            已售出
          </el-button>
          <el-button 
            :type="statusFilter === '下架' ? 'primary' : ''"
            @click="filterByStatus('下架')"
          >
            已下架
          </el-button>
        </el-button-group>
      </div>
      
      <div class="filter-right">
        <el-button 
          type="primary" 
          :icon="Plus" 
          @click="$router.push('/publish')"
        >
          发布新商品
        </el-button>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="goods-content">
      <!-- 加载状态 -->
      <div v-if="goodsStore.isLoading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>

      <!-- 商品网格 -->
      <div v-else-if="goodsStore.myGoodsList.length > 0" class="goods-grid">
        <div 
          v-for="goods in goodsStore.myGoodsList" 
          :key="goods.goodsId"
          class="goods-item"
        >
          <GoodsCard :goods="goods" />
          
          <!-- 商品操作 -->
          <div class="goods-actions">
            <el-button
              :icon="Edit"
              size="small"
              @click="editGoods(goods)"
            >
              编辑
            </el-button>
            <el-button
              v-if="goods.status === '在售'"
              :icon="Download"
              size="small"
              type="warning"
              @click="offlineGoods(goods.goodsId)"
            >
              下架
            </el-button>
            <el-button
              v-else-if="goods.status === '下架'"
              :icon="Upload"
              size="small"
              type="success"
              @click="onlineGoods(goods.goodsId)"
            >
              上架
            </el-button>
            <el-button
              :icon="Delete"
              size="small"
              type="danger"
              @click="deleteGoods(goods.goodsId)"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <el-empty description="暂无商品">
          <template #image>
            <div class="empty-icon">📦</div>
          </template>
          <el-button type="primary" @click="$router.push('/publish')">
            发布第一个商品
          </el-button>
        </el-empty>
      </div>
    </div>

    <!-- 编辑商品对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑商品"
      width="600px"
      :before-close="handleEditClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="商品标题" prop="title">
          <el-input v-model="editForm.title" maxlength="100" show-word-limit />
        </el-form-item>
        
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="4"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="出售价格" prop="price">
          <el-input-number
            v-model="editForm.price"
            :min="0.01"
            :precision="2"
            controls-position="right"
          />
        </el-form-item>
        
        <el-form-item label="原价">
          <el-input-number
            v-model="editForm.originalPrice"
            :min="0.01"
            :precision="2"
            controls-position="right"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit" :loading="goodsStore.isLoading">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useGoodsStore } from '@/stores/goodsStore'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import GoodsCard from '@/components/GoodsCard.vue'
import Pagination from '@/components/Pagination.vue'
import { 
  Plus, 
  Edit, 
  Delete, 
  Download, 
  Upload, 
  Refresh 
} from '@element-plus/icons-vue'

const goodsStore = useGoodsStore()
const router = useRouter()

// 筛选状态
const statusFilter = ref('all')

// 编辑对话框
const editDialogVisible = ref(false)
const editFormRef = ref()
const editForm = reactive({
  goodsId: null,
  title: '',
  description: '',
  price: null,
  originalPrice: null
})

// 编辑表单验证规则
const editRules = {
  title: [
    { required: true, message: '请输入商品标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度在5到100个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { min: 10, max: 1000, message: '描述长度在10到1000个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入出售价格', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' }
  ]
}

// 统计信息
const stats = computed(() => {
  const list = goodsStore.myGoodsList
  return {
    total: list.length,
    selling: list.filter(item => item.status === '在售').length,
    sold: list.filter(item => item.status === '已售').length,
    totalViews: list.reduce((sum, item) => sum + (item.viewCount || 0), 0)
  }
})

// 按状态筛选
const filterByStatus = async (status) => {
  statusFilter.value = status
  const params = status === 'all' ? {} : { status }
  await goodsStore.getMyGoods(params)
}

// 编辑商品
const editGoods = (goods) => {
  editForm.goodsId = goods.goodsId
  editForm.title = goods.title
  editForm.description = goods.description
  editForm.price = goods.price
  editForm.originalPrice = goods.originalPrice
  editDialogVisible.value = true
}

// 保存编辑
const saveEdit = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      const success = await goodsStore.updateGoods(editForm.goodsId, {
        title: editForm.title,
        description: editForm.description,
        price: editForm.price,
        originalPrice: editForm.originalPrice
      })
      
      if (success) {
        editDialogVisible.value = false
        await goodsStore.getMyGoods()
      }
    }
  })
}

// 关闭编辑对话框
const handleEditClose = () => {
  editDialogVisible.value = false
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

// 下架商品
const offlineGoods = async (goodsId) => {
  try {
    await ElMessageBox.confirm('确定要下架这个商品吗？', '确认操作', {
      type: 'warning'
    })
    
    const success = await goodsStore.updateGoods(goodsId, { status: '下架' })
    if (success) {
      await goodsStore.getMyGoods()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('下架商品失败:', error)
    }
  }
}

// 上架商品
const onlineGoods = async (goodsId) => {
  const success = await goodsStore.updateGoods(goodsId, { status: '在售' })
  if (success) {
    await goodsStore.getMyGoods()
  }
}

// 删除商品
const deleteGoods = async (goodsId) => {
  try {
    await ElMessageBox.confirm(
      '删除后无法恢复，确定要删除这个商品吗？',
      '确认删除',
      {
        type: 'error',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )
    
    const success = await goodsStore.deleteGoods(goodsId)
    if (success) {
      await goodsStore.getMyGoods()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  goodsStore.getMyGoods()
})
</script>

<style scoped>
.my-goods-view {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.page-header p {
  color: #666;
  font-size: 16px;
}

.stats-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  gap: 15px;
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  font-size: 32px;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

.goods-content {
  margin-bottom: 30px;
}

.loading-container {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.goods-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.goods-item {
  position: relative;
}

.goods-actions {
  position: absolute;
  bottom: 10px;
  left: 10px;
  right: 10px;
  display: flex;
  gap: 5px;
  background: rgba(255, 255, 255, 0.95);
  padding: 8px;
  border-radius: 6px;
  backdrop-filter: blur(10px);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.goods-item:hover .goods-actions {
  opacity: 1;
}

.empty-state {
  background: white;
  padding: 60px 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  text-align: center;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-section {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }
  
  .stat-card {
    padding: 20px;
  }
  
  .stat-icon {
    font-size: 24px;
    width: 50px;
    height: 50px;
  }
  
  .stat-number {
    font-size: 20px;
  }
  
  .filter-bar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .goods-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 15px;
  }
  
  .goods-actions {
    opacity: 1;
    position: static;
    margin-top: 10px;
    background: white;
    border: 1px solid #f0f0f0;
  }
}

@media (max-width: 480px) {
  .stats-section {
    grid-template-columns: 1fr;
  }
  
  .goods-grid {
    grid-template-columns: 1fr;
  }
}
</style>